﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Lamex.Library;
using Lamex.Interface;
using System.IO;

namespace Lamex.mTools.UI
{
    public partial class frmTL_Image_Accessories : frmBaseChild
    {
        string PartNo;

        DataTable dt = null;
        List<ImageList> lst = null;

        public frmTL_Image_Accessories()
        {
            InitializeComponent();
        }

        private void frmTL_Image_Accessories_Load(object sender, EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理

            layoutView1.OptionsBehavior.Editable = false;
            layoutView1.OptionsCustomization.AllowFilter = false;
            layoutView1.OptionsCustomization.AllowSort = false;
            layoutView1.OptionsView.ShowCardBorderIfCaptionHidden = false;
            layoutView1.OptionsView.ShowCardCaption = false;
            layoutView1.OptionsView.ShowCardLines = false;
            layoutView1.OptionsView.ShowHeaderPanel = false;
            layoutView1.OptionsView.ViewMode = DevExpress.XtraGrid.Views.Layout.LayoutViewMode.Column;

            changeDisplayState_MultiBox();

            pboxMulti_LayoutSizeAdjust();


        }

        //pboxMulti布局尺寸调整
        private void pboxMulti_LayoutSizeAdjust()
        {
            pboxMulti_Top.Height = pboxMulti_ISO.Height / 6;
            pboxMulti_Bottom.Height = pboxMulti_ISO.Height / 6;
            pboxMulti_Left.Height = pboxMulti_ISO.Height / 6;
            pboxMulti_Right.Height = pboxMulti_ISO.Height / 6;
            pboxMulti_Front.Height = pboxMulti_ISO.Height / 6;
            pboxMulti_Back.Height = pboxMulti_ISO.Height / 6;

            int width = 33;
            pboxMulti_ISO.Width = splitContainer1.Panel1.Width - width;
            pboxMulti_Top.Width = width;
            pboxMulti_Bottom.Width = width;
            pboxMulti_Left.Width = width;
            pboxMulti_Right.Width = width;
            pboxMulti_Front.Width = width;
            pboxMulti_Back.Width = width;

            sbtnMulti_First.Width = splitContainer1.Panel1.Width / 4;
            sbtnMulti_Previous.Width = splitContainer1.Panel1.Width / 4;
            sbtnMulti_Next.Width = splitContainer1.Panel1.Width / 4;
            sbtnMulti_Last.Width = splitContainer1.Panel1.Width / 4;
        }

        private void frmTL_Image_Accessories_Resize(object sender, EventArgs e)
        {
            //splitContainer1.SplitterDistance = this.Width - 210;
            //pboxMulti_ISO.Width = splitContainer1.Panel1.Width - 210;

            //pboxMulti_LayoutSizeAdjust();

            //pictureBox控件图片自适应
            //pictureBoxAutoAdjust();
        }

        private void sbtnGetPath_Click(object sender, EventArgs e)
        {
            XtraFolderBrowserDialog folder = new XtraFolderBrowserDialog();
            FolderBrowserDialog fb = new FolderBrowserDialog();
            //设置默认根目录是桌面
            folder.RootFolder = Environment.SpecialFolder.Desktop;
            folder.SelectedPath = @"L:\MES\SysSource\Image\Accessory\";//用绝对路径时不能正确指向
            //folder.SelectedPath = @"D:\Temp\";
            //设置对话框说明
            folder.Description = "请选择文件搜索路径:";
            if (folder.ShowDialog() == DialogResult.OK)
            {
                txtSearchPath.Text = folder.SelectedPath;
            }
        }

        private void sbtnView_Click(object sender, EventArgs e)
        {           
            //重置（清空）所有图片控件显示
            pictureBoxImageClear();
            
            //右侧gridControl控件加载图像
            gridControlImageDataAdd();         
        }

        //右侧gridControl控件图片加载
        private void gridControlImageDataAdd()
        {
            //只显示文件名包含"-ISO"的图片文件
            //1、查询表【TOOL_Aceessory_Image_List】
            //2、返回包含【tboxFileName】的字段【FILE_NAME】值,
            //3、或字段【FILE_DESC】包含【textBoxDesc】并返回【FILE_NAME】值，且在
            //4、在【txtSearchPath】路径下，查找包含2、3返回【FILE_NAME】及"ISO"字符串的图片文件
            //5、将4返回的图片文件加载到gridControl1中
            pictureBoxImageClear();
            this.gridControl1.DataSource = null;
            string strWhere = "";
            string sql = @"select * from [dbo].[TOOL_Aceessory_Image_List] where 1=1 ";

            if (!string.IsNullOrEmpty(tboxFileName.Text))
            {
                strWhere += " and FILE_NAME='" + tboxFileName.Text + "'";
            }
            if (!string.IsNullOrEmpty(textBoxDesc.Text))
            {
                strWhere += " and FILE_DESC like'%" + textBoxDesc.Text + "%'";
            }
            sql += strWhere;
            dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(sql);
            searchControl1.Properties.Items.Clear();
            if (dt.Rows != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    searchControl1.Properties.Items.Add(dr["FILE_NAME"]);
                }
            }

            lst = new List<ImageList>();
            lst.Clear();
            foreach (DataRow dr in dt.Rows)
            {
                ImageList model = new ImageList();
                string strPath = txtSearchPath.Text.ToString();
                var files = new DirectoryInfo(strPath).GetFiles().Where(p => p.Extension.ToLower() != ".db" && p.Name.Contains(dr["FILE_NAME"].ToString()) && p.Name.ToLower().Contains("iso"));
                foreach (FileInfo info in files)
                {
                    model.Name = info.Name;
                    model.PathFull = info.FullName;
                    model.pathImage = Image.FromFile(info.FullName);
                    model.PartNo = dr["FILE_NAME"].ToString();
                    lst.Add(model);
                }
            }

            //string strPath = txtSearchPath.Text.ToString();

            ////var files = new DirectoryInfo(strPath).GetFiles().Where(p => p.Extension.ToLower() != ".db");
            //var files = new DirectoryInfo(strPath).GetFiles().Contains("").Where(p => p.Extension.ToLower() != ".db");

            //var data = files.Select(d =>
            //{
            //    return new { Name = d.Name, Image = Image.FromFile(d.FullName), Paths = d.FullName };
            //});

            this.gridControl1.BeginUpdate();
            this.gridControl1.DataSource = lst;
            this.gridControl1.EndUpdate();
        }

        //pictureBox控件加载图片
        private void pictureBoxAddImage()
        {
            if (rbtnMultiBox.Checked == true)
            {
                addImage_MultiBox();
            }
            else if (rbtnNineBox.Checked == true)
            {
                addImage_NineBox();
            }
        }

        //pictureBox控件图片自适应
        private void pictureBoxAutoAdjust()
        {
            if (rbtnMultiBox.Checked == true)
            {
                if (pboxMulti_ISO.Image != null)
                    imageDisplayAdjust(pboxMulti_ISO);
                if (pboxMulti_Top.Image != null)
                    imageDisplayAdjust(pboxMulti_Top);
                if (pboxMulti_Bottom.Image != null)
                    imageDisplayAdjust(pboxMulti_Bottom);
                if (pboxMulti_Left.Image != null)
                    imageDisplayAdjust(pboxMulti_Left);
                if (pboxMulti_Right.Image != null)
                    imageDisplayAdjust(pboxMulti_Right);
                if (pboxMulti_Front.Image != null)
                    imageDisplayAdjust(pboxMulti_Front);
                if (pboxMulti_Back.Image != null)
                    imageDisplayAdjust(pboxMulti_Back);
            }
            else if (rbtnNineBox.Checked == true)
            {
                if (pboxNine_ISO.Image != null)
                    imageDisplayAdjust(pboxNine_ISO);
                if (pboxNine_Top.Image != null)
                    imageDisplayAdjust(pboxNine_Top);
                if (pboxNine_Bottom.Image != null)
                    imageDisplayAdjust(pboxNine_Bottom);
                if (pboxNine_Left.Image != null)
                    imageDisplayAdjust(pboxNine_Left);
                if (pboxNine_Right.Image != null)
                    imageDisplayAdjust(pboxNine_Right);
                if (pboxNine_Front.Image != null)
                    imageDisplayAdjust(pboxNine_Front);
                if (pboxNine_Back.Image != null)
                    imageDisplayAdjust(pboxNine_Back);
            }

        }
        
        //加载当前选择产品/配件图片到左侧窗格
        #region 图像控件文件加载

        private void addImage_MultiBox()
        {
            string strPath = txtSearchPath.Text;
            if (string.IsNullOrEmpty(txtSearchPath.Text))
                return;
            var files = new DirectoryInfo(strPath).GetFiles().Where(p => p.Extension.ToLower() != ".db" && p.Name.Contains(PartNo) );
            foreach (FileInfo info in files)
            { 
                if(info.Name.ToLower().Contains("iso"))
                    pboxMulti_ISO.Load(info.FullName);
                else if (info.Name.ToLower().Contains("top"))
                    pboxMulti_Top.Load(info.FullName);
                else if (info.Name.ToLower().Contains("bottom"))
                    pboxMulti_Bottom.Load(info.FullName);
                else if (info.Name.ToLower().Contains("left"))
                    pboxMulti_Left.Load(info.FullName);
                else if (info.Name.ToLower().Contains("right"))
                    pboxMulti_Right.Load(info.FullName);
                else if (info.Name.ToLower().Contains("front"))
                    pboxMulti_Front.Load(info.FullName);
                else if (info.Name.ToLower().Contains("back"))
                    pboxMulti_Back.Load(info.FullName);
            }
        }

        private void addImage_NineBox()
        {
            string strPath = txtSearchPath.Text;
            if (string.IsNullOrEmpty(txtSearchPath.Text))
                return;
            var files = new DirectoryInfo(strPath).GetFiles().Where(p => p.Extension.ToLower() != ".db" && p.Name.Contains(PartNo) );
            foreach (FileInfo info in files)
            {
                if (info.Name.ToLower().Contains("iso"))
                    pboxNine_ISO.Load(info.FullName);
                else if (info.Name.ToLower().Contains("top"))
                    pboxNine_Top.Load(info.FullName);
                else if (info.Name.ToLower().Contains("bottom"))
                    pboxNine_Bottom.Load(info.FullName);
                else if (info.Name.ToLower().Contains("left"))
                    pboxNine_Left.Load(info.FullName);
                else if (info.Name.ToLower().Contains("right"))
                    pboxNine_Right.Load(info.FullName);
                else if (info.Name.ToLower().Contains("front"))
                    pboxNine_Front.Load(info.FullName);
                else if (info.Name.ToLower().Contains("back"))
                    pboxNine_Back.Load(info.FullName);
            }
        }

        #endregion

        #region 切换显示方式

        private void rbtnMultiBox_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnMultiBox.Checked == true)
            {
                changeDisplayState_MultiBox();
                pboxMulti_LayoutSizeAdjust();
            }

            //pictureBox控件加载图片
            pictureBoxAddImage();

            //pictureBox控件图片自适应
            pictureBoxAutoAdjust();
        }

        private void rbtnNineBox_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnNineBox.Checked == true)
            {
                changeDisplayState_NineBox();
            }

            //pictureBox控件加载图片
            pictureBoxAddImage();

            //pictureBox控件图片自适应
            pictureBoxAutoAdjust();
        }

        private void changeDisplayState_MultiBox()
        {
            layoutControlMultiBox.Dock = DockStyle.Fill;
            layoutControlMultiBox.Visible = true;
            layoutControlNineBox.Width = 0;
            layoutControlNineBox.Visible = false;

            pboxMulti_LayoutSizeAdjust();
        }

        private void changeDisplayState_NineBox()
        {
            layoutControlMultiBox.Width = 0;
            layoutControlMultiBox.Visible = false;
            layoutControlNineBox.Dock = DockStyle.Fill;
            layoutControlNineBox.Visible = true;
        }

        #endregion

        private void searchControl1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(e.KeyChar==13)
            {
                pictureBoxImageClear();
                this.gridControl1.DataSource = null;
                if (lst.Count!= 0)
                {
                    List<ImageList> _lst = lst.Where(p=>p.PartNo==searchControl1.Text).ToList();
                        //dt.Select(" FILE_NAME='"+searchControl1.Text+"'");
                    if (_lst.Count!=0)
                    {
                        
                        //DataTable _dt = drs.CopyToDataTable();
                        //List<ImageList> lst = new List<ImageList>();
                        //foreach (DataRow d in _dt.Rows)
                        //{
                        //    ImageList model = new ImageList();
                        //    string strPath = txtSearchPath.Text.ToString();
                        //    var files = new DirectoryInfo(strPath).GetFiles().Where(p => p.Extension.ToLower() != ".db" && p.Name.Contains(d["FILE_NAME"].ToString()) && p.Name.ToLower().Contains("iso"));
                        //    foreach (FileInfo info in files)
                        //    {
                        //        model.Name = info.Name;
                        //        model.PathFull = info.FullName;
                        //        model.pathImage = Image.FromFile(info.FullName);
                        //        model.PartNo = d["FILE_NAME"].ToString();
                        //        lst.Add(model);
                        //    }
                        //}
                        this.gridControl1.BeginUpdate();
                        this.gridControl1.DataSource = _lst;
                        this.gridControl1.EndUpdate();
                    }
                    else
                    {
                        this.gridControl1.BeginUpdate();
                        this.gridControl1.DataSource = null;
                        this.gridControl1.EndUpdate();
                    }
                }
            }

        }

        private void searchControl1_EditValueChanged(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(searchControl1.Text))
            {
                this.gridControl1.BeginUpdate();
                this.gridControl1.DataSource = lst;
                this.gridControl1.EndUpdate();
            }
            else
            {
                List<ImageList> _lst = lst.Where(p => p.PartNo == searchControl1.Text).ToList();
                if (_lst.Count != 0)
                {
                    this.gridControl1.BeginUpdate();
                    this.gridControl1.DataSource = _lst;
                    this.gridControl1.EndUpdate();
                }
                else
                {
                    this.gridControl1.BeginUpdate();
                    this.gridControl1.DataSource = null;
                    this.gridControl1.EndUpdate();
                }
            }
        }

        #region 单击【按钮】方式切换图片

        private void sbtnMulti_First_Click(object sender, EventArgs e)
        {
            layoutView1.FocusedRowHandle = 0;
        }

        private void sbtnMulti_Previous_Click(object sender, EventArgs e)
        {
            layoutView1.FocusedRowHandle = layoutView1.FocusedRowHandle - 1;
        }

        private void sbtnMulti_Next_Click(object sender, EventArgs e)
        {
            layoutView1.FocusedRowHandle = layoutView1.FocusedRowHandle + 1;
        }

        private void sbtnMulti_Last_Click(object sender, EventArgs e)
        {
            layoutView1.FocusedRowHandle = layoutView1.RowCount-1;
        }

        private void sbtnNine_First_Click(object sender, EventArgs e)
        {
            layoutView1.FocusedRowHandle = 0;
        }

        private void sbtnNine_Previous_Click(object sender, EventArgs e)
        {
            layoutView1.FocusedRowHandle = layoutView1.FocusedRowHandle - 1;
        }

        private void sbtnNine_Next_Click(object sender, EventArgs e)
        {
            layoutView1.FocusedRowHandle = layoutView1.FocusedRowHandle + 1;
        }

        private void sbtnNine_Last_Click(object sender, EventArgs e)
        {
            layoutView1.FocusedRowHandle = layoutView1.RowCount - 1;
        }

        #endregion

        //单击【缩略图】方式切换图片
        private void layoutView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            layoutView1_Click(null, null) ;
        }

        //加载当前选择产品/配件图片到左侧窗格
        private void layoutView1_Click(object sender, EventArgs e)
        {
            if (layoutView1.RowCount == 0)
                return;
            //pictureBox控件加载图片
            int irow = layoutView1.FocusedRowHandle;
            PartNo = layoutView1.GetFocusedRowCellValue("PartNo").ToString();

            pictureBoxImageClear();
            pictureBoxAddImage();

            //pictureBox控件图片自适应
            pictureBoxAutoAdjust();
        }

        //根据图片尺寸，适配PictureBox，即图片任意一边大于PictureBox对应边时，缩放；否则自适应
        private void imageDisplayAdjust(PictureBox pbox)
        {
            Bitmap bmp = new Bitmap(pbox.Image);

            if (bmp.Width > pbox.Width | bmp.Height > pbox.Height)
            {
                pbox.SizeMode = PictureBoxSizeMode.Zoom;
            }
            else
            {
                pbox.SizeMode = PictureBoxSizeMode.CenterImage;
            }
        }

        //重置（清空）所有图片控件显示
        private void pictureBoxImageClear()
        {
            pboxMulti_ISO.Image = null;
            pboxMulti_Top.Image = null;
            pboxMulti_Bottom.Image = null;
            pboxMulti_Left.Image = null;
            pboxMulti_Right.Image = null;
            pboxMulti_Front.Image = null;
            pboxMulti_Back.Image = null;
            pboxNine_ISO.Image = null;
            pboxNine_Top.Image = null;
            pboxNine_Bottom.Image = null;
            pboxNine_Left.Image = null;
            pboxNine_Right.Image = null;
            pboxNine_Front.Image = null;
            pboxNine_Back.Image = null;
        }

        #region 实例化标准功能

        public override void DoView(IButtonInfo sender)
        {
            sbtnView_Click(null, null);
            base.DoView(sender);
        }

        private void 隐藏选项区ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panelTop.Height = 0;
        }

        private void 显示选项区ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            panelTop.Height = 60;
        }

        #endregion
    }
}